<?php

namespace Modules\Common\Support\Upload\Uses;


use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Modules\Basic\Models\UploadFile;

class LocalUpload extends Upload
{
    /**
     * upload
     *
     * @return array
     */
    public function upload(): array
    {
        return $this->addUrl($this->getUploadPath());
    }

    /**
     * app url
     *
     * @param $path
     * @return mixed
     */
    protected function addUrl($path): mixed
    {
        $file_path = public_path('uploads/' . $path['path']);
        $path['path'] = getenv('UPLOAD_URL') . '/' .
            Str::of($path['path'])->replace('\\', '/')->toString();
        UploadFile::create([
            'url' => $path['path'],
            'file_name' => $path['originalName'],
            'file_ext' => $path['ext'],
            'file_type' => $path['type'],
            'file_size' => $path['size'],
            'file_path' => $file_path,
        ]);
        return $path;
    }


    /**
     * local upload
     *
     * @return string
     */
    protected function localUpload(): string
    {
        $this->checkSize();

        $storePath = 'uploads' . DIRECTORY_SEPARATOR . date('Y-m-d', time());

        $filename = $this->generateImageName($this->getUploadedFileExt());

        Storage::build([
            'driver' => 'local',
            'root' => $storePath
        ])->put($filename, $this->file->getContent());
        // 上传OSS/OBS
        $object_key = date('Y-m-d') . '/' . $filename;
        if (getenv('UPLOAD_DRIVER') == 'OSS') {
            oss_upload_file($object_key, public_path($storePath . '/' . $filename));
        }
        if (getenv('UPLOAD_DRIVER') == 'OBS') {
            obs_upload_file($object_key, public_path($storePath . '/' . $filename));
        }
        return $object_key;
    }
}
